package setting

import (
	"fmt"
	"github.com/natefinch/lumberjack"
	"go.uber.org/zap"
	"go.uber.org/zap/zapcore"
	"gopkg.in/ini.v1"
	"os"
)

func initLogger(configFile *ini.File) error {
	section := configFile.Section("log")
	level := section.Key("level").MustString("error")
	var logLevel zapcore.Level
	err := logLevel.UnmarshalText([]byte(level))
	if err != nil {
		return fmt.Errorf("invalid log level: %v", level)
	}
	fileLogger := configFileLogger(section, logLevel)
	var core zapcore.Core
	if fileLogger != nil {
		core = zapcore.NewTee(
			configConsoleLogger(logLevel),
			fileLogger,
		)
	} else {
		core = configConsoleLogger(logLevel)
	}
	zap.ReplaceGlobals(zap.New(core, zap.AddCaller()))
	return nil
}

func configConsoleLogger(level zapcore.Level) zapcore.Core {
	return zapcore.NewCore(zapcore.NewConsoleEncoder(zap.NewDevelopmentEncoderConfig()), zapcore.Lock(os.Stdout), level)
}

func configFileLogger(section *ini.Section, level zapcore.Level) zapcore.Core {
	logFileName := section.Key("file_name").MustString("")
	if logFileName != "" {
		lumberJackLogger := &lumberjack.Logger{
			Filename:   logFileName,
			MaxSize:    section.Key("max_size").MustInt(10),
			MaxBackups: section.Key("max_backups").MustInt(3),
			MaxAge:     section.Key("max_age").MustInt(7),
			Compress:   section.Key("compress").MustBool(false),
		}
		sync := zapcore.AddSync(lumberJackLogger)
		return zapcore.NewCore(zapcore.NewJSONEncoder(zap.NewDevelopmentEncoderConfig()), sync, level)
	}
	return nil
}
